package com.oh.core.common.utils;

import com.oh.core.common.base.MessageService;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务类
 */
public class ServiceRouteFactory {
    // 保存服务类
    private static final Map<Byte, MessageService> serviceMap = new ConcurrentHashMap<Byte, MessageService>();

    /**
     * 根据指令，获取消息处理服务
     * @param command 消息指令
     * @return
     * @throws Exception
     */
    public static Optional<MessageService> getService(Byte command) throws Exception {
        Optional<MessageService> optionalService = Optional.ofNullable(serviceMap.get(command));
        if(optionalService.isPresent()){
            return optionalService;
        }else{
            throw new Exception("找不到服务指令【"+command+"】");
        }
    }

    /**
     * 注册消息处理服务
     * @param command 指令
     * @param messageService 消息服务
     */
    public static void register(Byte command , MessageService messageService) {
        Assert.notNull(command, "注册的服务不能为空");
        serviceMap.put(command, messageService);
    }
}
